<?php
/*
Plugin Name: VTP banery
Plugin URI: http://www.dudyland.sk
Description: VTP banery
Version: 0.1
Author: Peter Turza, Pavol Martiniak
Author URI: http://www.dudyland.sk
*/
?>
<?php
class VTPBanners {

    private $wpdb;

    function __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
        add_action('admin_menu', array(&$this, 'bannersMenu'));
        // registruje skripty
        wp_register_script('jquery-validate', get_bloginfo(url).'/wp-includes/js/validate/jquery.validate.js');
        wp_register_script('myscript', get_bloginfo(url).'/wp-includes/js/validate/myscript.js');                    
    }

    function bannersMenu() {
        add_menu_page('VTP Banners', 'Bannery', 'edit_pages', 'bannersMenu', array(&$this, 'listAll'));
        add_submenu_page('bannersMenu', 'Pridať nový banner', 'Pridať nový banner', 'edit_pages', 'addBanner', array(&$this, 'addBanner'));
        // nacita skripty
        wp_enqueue_script('jquery-validate');
        wp_enqueue_script('myscript');                        
    }

    function listAll() {

        if ($_GET['action'] == 'edit') {
            // formular na editaciu zaznamov
            $id = $_GET['id'];
            $this->edit($id);
            return;
        }
        if ($_GET['action'] == 'delete') {
            $id = $_GET['id'];
            $this->wpdb->query('DELETE FROM wp_banners WHERE id = '.$id);
            // vymazanie uploadovanych obrazkov
            $uploadDirArray = wp_upload_dir();
            $mydir = $uploadDirArray['basedir'].'/banners/'.$id.'/';
            $d = dir($mydir);
            while($entry = $d->read()) {
                if ($entry!= "." && $entry!= "..") {
                    unlink($mydir.$entry);
                }
            }
            $d->close();
            rmdir($mydir);
        } else {
            // listing
            echo '<div id="wrap">';
            echo '<h2>Zoznam bannerov</h2>';
            $result = $this->wpdb->get_results("SELECT * FROM wp_banners");
            echo '<table class="form-table">';
            foreach ($result as $r) {
                $uploadDirArray = wp_upload_dir();
                echo '<tr><td><img src="'.$uploadDirArray['baseurl'].'/banners/'.$r->id.'/'.$r->image.'"/></td><td>'.(($r->active==1)?'Aktívny':'Neaktívny').'</td><td><a href="?page=bannersMenu&action=edit&id='.$r->id.'">Upraviť</a></td><td><a href="?page=bannersMenu&action=delete&id='.$r->id.'" onclick="return confirmDelete(\''.$r->id.': '.$r->image.'\')">Zmazať</a></td></tr>';
            }
            echo '</table>';
            echo '</div>';
        }
    }

    /**
    * @desc Zobrazi formular a pridava zaznam do DB.
    */
    function addBanner() {
        if (!isset($_POST['submitted'])) { // show form

            echo '<div id="wrap">';
            echo '<h3>Pridať nový banner</h3>';
            echo '<p>Rozmery bannera 750 x 75</p>';

            echo '<form action="'.$_SERVER['REQUEST_URI'].'" id="addBanner" method="post" enctype="multipart/form-data">';
            echo '<table class="form-table">';
            echo '<tr><td><label for="bannerImage">Banner: *</label></td>';
            echo '<td><input type="file" name="bannerImage" id="bannerImage" /></td></tr>';

            echo '<tr><td><label for="active">Aktívny: </label></td>';
            echo '<td><input type="checkbox" name="active" id="active" /></td></tr>';

            echo '<tr><td><label for="link">Link: *</label></td>';
            echo '<td><input type="text" name="link" id="link" /></td></tr>';

            echo '<input type="hidden" name="submitted" value="true">';

            echo '<tr><td></td><td><input type="submit" value="Pridať banner" /></td></tr>';
            echo '</table>';
            echo '</form>';
            echo '<script type="text/javascript">
                    jQuery("#addBanner").validate({
                        rules: {
                            bannerImage: {required: true, accept: "jpe?g|gif|png"},
                            link: {required: true, url: true}
                        }
                    });
                    </script>';
            echo '</div>';
        } else {
            // validation & insertion
            $image = $_FILES['bannerImage']['name'];
            $link = trim($_POST['link']);
            if ($link != '') {
                $data = array('id' => 'NULL', 'image' => $image, 'active' => (empty($_POST['active'])? 0 : 1), 'link'=>$link);
            } else {
                $data = array('id' => 'NULL', 'image' => $image, 'active' => (empty($_POST['active'])? 0 : 1));
            }

            // vloz do DB
            $this->wpdb->insert('wp_banners', $data);
            $lastId = $this->wpdb->insert_id;

            // presun foto do upload priecinku
            $upload = VTPBanners::my_wp_upload_bits($_FILES["bannerImage"]["name"], null, file_get_contents($_FILES["bannerImage"]["tmp_name"]), null, '/banners/'.$lastId );
            unset($_POST['submitted']);

            // ak vsetko prebehlo, presmeruj na listAll
            unset($_GET['action']);
            $this->listAll();
        }
    }

    /**
    * @desc Formular na editaciu zaznamov.
    */
    private function edit($id) {
        if (!isset($_POST['submitted'])) { // show form

            $banner = $this->wpdb->get_row('SELECT * FROM wp_banners WHERE id = '.$id);
            $uploadDirArray = wp_upload_dir();
            echo '<div id="wrap">';
            echo '<h2>Upraviť banner "'.$banner->id.': '.$banner->image.'"';
            echo '<br /><br />';
            echo '<img src="'.$uploadDirArray['baseurl'].'/banners/'.$banner->id.'/'.$banner->image.'"/></td></tr>';
            echo '<br /><br />';
            echo '<form action="'.$_SERVER['REQUEST_URI'].'" id="editBanner" method="post" >';
            echo '<table class="form-table">';
            echo '<tr><td><label for="active">Aktívny: </label></td>';
            if ($banner->active == 1) {
                echo '<td><input type="checkbox" name="active" id="active" checked="checked"/></td></tr>';
            } else {
                echo '<td><input type="checkbox" name="active" id="active"/></td></tr>';
            }
            echo '<tr><td><label for="link">Link: *</label></td>';
            echo '<td><input type="text" name="link" id="link" value="'.$banner->link.'"/></td></tr>';
            echo '<input type="hidden" name="submitted" value="true">';
            echo '<tr><td></td><td><input type="submit" value="Upraviť banner" /></td></tr>';
            echo '</table>';
            echo '</form>';
            echo '<script type="text/javascript">
                    jQuery("#editBanner").validate({
                        rules: {
                            link: {required: true, url: true}
                        }
                    });
                    </script>';
            echo '</div>';
        } else {
            $link = trim($_POST['link']);
            if ($link != '') {
                $data = array('active' => (!isset($_POST['active'])? 0 : 1), 'link' => $link);
            } else {
                $data = array('active' => (!isset($_POST['active'])? 0 : 1));
            }
            
            $this->wpdb->update('wp_banners', $data, array( 'id' => $id ));
            unset($_POST['submit']);

            // ak je vsetko OK, presmeruj na listall
            unset($_GET['action']);
            $this->listAll();
        }
    }

    /**
    * @desc Upravena funkcia pre upload suboru z functions.php.
    */
    private static function my_wp_upload_bits( $name, $deprecated, $bits, $time = null, $subFolder = '' ) {
        if ( empty( $name ) )
            return array( 'error' => __( 'Empty filename' ) );

        $wp_filetype = wp_check_filetype( $name );
        if ( !$wp_filetype['ext'] )
            return array( 'error' => __( 'Invalid file type' ) );

        $upload = wp_upload_dir( $time );

        if ( $upload['error'] !== false )
            return $upload;

        $filename = wp_unique_filename( $upload['path'], $name );

        $new_file = $upload['basedir'] . $subFolder . "/$filename";
        if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
            $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
            return array( 'error' => $message );
        }

        $ifp = @ fopen( $new_file, 'wb' );
        if ( ! $ifp )
            return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );

        @fwrite( $ifp, $bits );
        fclose( $ifp );
        // Set correct file permissions
        $stat = @ stat( dirname( $new_file ) );
        $perms = $stat['mode'] & 0007777;
        $perms = $perms & 0000666;
        @ chmod( $new_file, $perms );

        // Compute the URL
        $url = $upload['url'] . "/$filename";

        return array( 'file' => $new_file, 'url' => $url, 'error' => false );
    }

    function getBanner($id) {
        $banner = $this->wpdb->get_row('SELECT * FROM wp_banners WHERE id = '.$id);
        $uploadDirArray = wp_upload_dir();
        return array('image'=>$uploadDirArray['baseurl'].'/banners/'.$banner->id.'/'.$banner->image,
            'link'=>$banner->link);
    }

    function getActiveBanners() {
        $activeBanners = $this->wpdb->get_results('SELECT * FROM wp_banners WHERE active = 1');
        $uploadDirArray = wp_upload_dir();
        $banners = array();
        foreach($activeBanners as $banner) {
            $banners[]=array('image'=>$uploadDirArray['baseurl'].'/banners/'.$banner->id.'/'.$banner->image,
                'link'=>$banner->link);
        }
        return $banners;
    }

}

add_action('plugins_loaded', create_function('','global $vtpBanners; $vtpBanners = new VTPBanners();'));

?>